package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppNewsLogMapper;
import com.eco.fanliapp.entity.AppNewsLog;
import com.eco.fanliapp.entity.MsgTemplate;
import com.eco.fanliapp.entity.SyNewsType;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.Convert;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.EmojiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 消息记录 服务层实现
 *
 * @author xiaoxx
 * @date 2019-05-14
 */
@Service
public class AppNewsLogServiceImpl extends ServiceImpl<AppNewsLogMapper, AppNewsLog> implements IAppNewsLogService {

    private static final Logger log = LoggerFactory.getLogger(AppNewsLogServiceImpl.class);

    @Autowired
    private AppNewsLogMapper appNewsLogMapper;
    @Autowired
    private IMsgTemplateService msgTemplateService;
    @Autowired
    private ISyNewsTypeService iSyNewsTypeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UpdateAppNewsLogService updateAppNewsLogService;

    /**
     * 查询消息记录信息
     *
     * @param tableId 消息记录ID
     * @return 消息记录信息
     */
    @Override
    public AppNewsLog selectAppNewsLogById(Integer tableId) {
        return appNewsLogMapper.selectAppNewsLogById(tableId);
    }

    /**
     * 查询消息记录列表
     *
     * @param appNewsLog 消息记录信息
     * @return 消息记录集合
     */
    @Override
    public List<AppNewsLog> selectAppNewsLogList(AppNewsLog appNewsLog) {
        return appNewsLogMapper.selectAppNewsLogList(appNewsLog);
    }

    /**
     * 新增消息记录
     *
     * @param appNewsLog 消息记录信息
     * @return 结果
     */
    @Override
    public int insertAppNewsLog(AppNewsLog appNewsLog) {
        appNewsLog.setCreateTime(System.currentTimeMillis());
        appNewsLog.setUpdateTime(System.currentTimeMillis());
        return appNewsLogMapper.insertAppNewsLog(appNewsLog);
    }

    /**
     * 修改消息记录
     *
     * @param appNewsLog 消息记录信息
     * @return 结果
     */
    @Override
    public int updateAppNewsLog(AppNewsLog appNewsLog) {
        appNewsLog.setUpdateTime(System.currentTimeMillis());
        return appNewsLogMapper.updateAppNewsLog(appNewsLog);
    }

    /**
     * 删除消息记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAppNewsLogByIds(String ids) {
        return appNewsLogMapper.deleteAppNewsLogByIds(Convert.toStrArray(ids));
    }

    //消息入库操作
    @Override
    public void newsType(Long userId, int msgType, BigDecimal money, String... templateVariables) {
        try {
            log.info("发送消息请求参数{}:{}:{}:{}", userId, msgType, money.toString(), templateVariables);
            // TODO Auto-generated method newsType
            AppNewsLog appNewsLog = new AppNewsLog();
            appNewsLog.setUserId(userId);
            //收入消息头像
            appNewsLog.setIconUrl(ApiEnum.MSG_INCOME_ICON);
            appNewsLog.setJumpType(msgType);
            appNewsLog.setCreateTime(System.currentTimeMillis());
            appNewsLog.setUpdateTime(System.currentTimeMillis());
            SyNewsType syNewsType = iSyNewsTypeService.getById(msgType);

            if (syNewsType != null && syNewsType.getEnable() == 1 && syNewsType.getDeleted() == 0) {
                //钱保留两位小数
                if (!StringUtils.isEmpty(money)) {
                    money = money.setScale(2, BigDecimal.ROUND_DOWN);
                }

                appNewsLog.setNewsType(msgType);
                String str = syNewsType.getNewsContent();

                //templateVariables是变量替换值
                if (templateVariables != null && templateVariables.length > 0) {
                    for (String templateVariable : templateVariables) {
                        str = str.replaceFirst("\\{.+?}", templateVariable);
                    }

                }

                appNewsLog.setNewsTitle(syNewsType.getNewsTitle());
                appNewsLog.setNewsContent(str);
                appNewsLog.setNewsMoney(money);
            }

            if (appNewsLog.getNewsType() != null) {
                log.info("消息插入数据库====开始");
                long seconds = System.currentTimeMillis() / 1000;
                if (appNewsLog != null) {
                    redisTemplate.opsForList().rightPushAll("InsertAppMessage" + seconds, appNewsLog);
                }
                Object insertAppMessageMaxSend = redisTemplate.opsForValue().get("InsertAppMessageMaxSend");
                Integer i = 0;
                if (insertAppMessageMaxSend == null || Long.parseLong(insertAppMessageMaxSend.toString()) < seconds) {
                    redisTemplate.opsForValue().set("InsertAppMessageMaxSend", seconds);
                    updateAppNewsLogService.inDatabase(seconds);
                }
                //int i = appNewsLogMapper.insertAppNewsLog(appNewsLog);
                log.info("消息插入数据库====结束{}", i);

//                if (i > 0) {
                if (msgType == 5 || msgType == 502 || msgType == 603 || msgType == 605 || msgType == 606 || msgType == 607 || msgType == 703) {
                    log.info("message消息入库成功{}", i);
                    JpushMessage.jiGuangPushMesageAndroid(msgType, EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsTitle()), String.valueOf(userId), EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsContent()));
                    JpushMessage.jiGuangPushMesageIos(msgType, EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsTitle()), String.valueOf(userId), EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsContent()));
                }
//                } else {
//                    log.info("message消息入库失败{}", i);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("==========发送消息异常==========={}", e.getMessage());
        }

    }

    //获取我的消息列表按照时间倒叙排列
    @Override
    public ServerResponse<List<AppNewsLog>> getMessageList(Long appUserId, Integer pageNum,
                                                           Integer pageSize, Integer msgType) {
        // TODO Auto-generated method selectAppNewsLogListLIMIT
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        List<AppNewsLog> newsLogs = appNewsLogMapper.getMessageList(appUserId, pageNum, pageSize, msgType);
//        List<AppNewsLog> news = new ArrayList<AppNewsLog>();
        for (AppNewsLog appNewsLog : newsLogs) {
            try {
                appNewsLog.setDateRemark(DateFormatUtils.stampToDate2(appNewsLog.getCreateTime(), DateFormatUtils.STANDARD_FORMAT6));
            } catch (Exception e) {

            }
            appNewsLog.setNewsTitle(EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsTitle()));
            appNewsLog.setNewsContent(EmojiUtil.resolveToEmojiFromByte(appNewsLog.getNewsContent()));
//            //后台推送
//            if (msgType == 1) {
//                //活动消息
//                log.info("message用户id{}消息类型={}", appNewsLog.getUserId(), appNewsLog.getNewsType());
//                news.add(appNewsLog);
//            } else if (msgType == 2) {
//                //收入消息
//                log.info("message用户id{}消息类型={}", appNewsLog.getUserId(), appNewsLog.getNewsType());
//                news.add(appNewsLog);
//            }
        }
        if (newsLogs.size() > 0) {
            return ServerResponse.createBySuccess("数据获取成功", newsLogs);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多消息了");
        }
    }

    @Override
    public ServerResponse AllMessageToRead(Long appUserId, String msgType) {
        List<AppNewsLog> appNewsLogList = appNewsLogMapper.selectUnreadLogs(appUserId, msgType);
        List<String> tableIdList = new ArrayList<>();
        for (AppNewsLog appNewsLog : appNewsLogList) {
            tableIdList.add(String.valueOf(appNewsLog.getTableId()));
        }
        long seconds = System.currentTimeMillis() / 1000;
        if (tableIdList != null && tableIdList.size() > 0) {
            redisTemplate.opsForList().rightPushAll("AllMessageToRead" + seconds, tableIdList);
        }
        Object allMessageToReadMaxSend = redisTemplate.opsForValue().get("AllMessageToReadMaxSend");
        if (allMessageToReadMaxSend == null || Long.parseLong(allMessageToReadMaxSend.toString()) < seconds) {
            redisTemplate.opsForValue().set("AllMessageToReadMaxSend", seconds);
            updateAppNewsLogService.toDatabase(seconds);
        }
        return ServerResponse.createBySuccess("操作成功", true);
//        List<AppNewsLog> appNewsLogList = appNewsLogMapper.selectUnreadLogs(appUserId, msgType);
//        //redisTemplate.opsForValue().set("appUserIdAppNewsLogList",appNewsLogList);
//
//        //修改是否已读的状态
//        if (appNewsLogList.size() > 0) {
//            int i = appNewsLogMapper.MessageToReadList(appUserId, appNewsLogList);
//            if (i >= 0) {
//                log.info("message消息已读成功{}", i);
//                return ServerResponse.createBySuccess("操作成功", true);
//            }
//            log.info("message消息已读失败{}", i);
//            return ServerResponse.createByError("操作失败", false);
//        } else {
//            return ServerResponse.createBySuccessCodeMessage(201, "沒有未读消息");
//        }
    }

    //设置消息已读
    @Override
    public ServerResponse MessageToRead(Long appUserId, String ids) {
        if (com.eco.fanliapp.utils.StringUtils.isNotNull(ids)) {
            List<String> tableId = Arrays.asList(Convert.toStrArray(ids));
            long seconds = System.currentTimeMillis() / 1000;
            //存redis
            if (tableId != null && tableId.size() > 0) {
                redisTemplate.opsForList().rightPushAll("AllMessageToRead" + seconds, tableId);
            }
            Object allMessageToReadMaxSend = redisTemplate.opsForValue().get("AllMessageToReadMaxSend");
            if (allMessageToReadMaxSend == null || Long.parseLong(allMessageToReadMaxSend.toString()) < seconds) {
                redisTemplate.opsForValue().set("AllMessageToReadMaxSend", seconds);
                updateAppNewsLogService.toDatabase(seconds);
            }
            return ServerResponse.createBySuccess("数据操作成功", true);

//            int i = appNewsLogMapper.MessageToRead(appUserId, Convert.toStrArray(ids));
//            if (i >= 0) {
//                return ServerResponse.createBySuccess("数据操作成功", true);
//            } else {
//                return ServerResponse.createByErro·r("操作失败", false);
//            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(401, "ids不能为空");
        }

    }

    //获取未读消息
    @Override
    public ServerResponse getNoReadMessage(Long appUserId, String msgType) {

        Integer count = appNewsLogMapper.getNoReadMessage(appUserId, msgType);
        if (count > 0) {
            Map<String, String> map = new HashMap();
            map.put("noReadNumber", count.toString());
            return ServerResponse.createBySuccess("数据获取成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "沒有未读消息");
        }
    }


    @Override
    public Integer findFenSiCount(Long userId) {
        // TODO Auto-generated method findFenSiCount 查询用户邀请次数
        return appNewsLogMapper.findFenSiCount(userId);
    }

    @Override
    public ServerResponse<List<AppNewsLog>> getRedEnvelopes(Long userId) {
        return ServerResponse.createBySuccess("数据获取成功", appNewsLogMapper.getRedEnvelopes(userId));
    }


    public static void main(String args[]) {
        String newsFs = "我是好人{大家好好吃饭吧}";
        String templateVariable = "错误的消息";
        newsFs = newsFs.replaceFirst("\\{.+?}", templateVariable);
    }
}
